/**
 * function{
 * 	hasChinese:判断当前对象中是否包含中文字符,
 * 	trim:解决IE 对jquery Trim方法的兼容性,
 * 	startWith:判断当前对象是否以字符开始,
 * 	endWith:判断字符串是否以字符结束,
 *  getFileUrl:获取本地资源文件的路径,
 *  preImg:预览本地图片,
 *  getUrlParam:获取URL参数列表,
 *  copyToClipboard:一键复制,
 *  isNull:判断对象是否为空,
 *  formatDateToEn:将日期转换成英文格式 2016-1-1 --> 01 Jan 2016
 * }
 * 
 * @version     v1.0
 * @date 		2016-09-30
 */


/**
 * IE不支持console
 */
window.console = window.console || (function () {
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
    = c.clear = c.exception = c.trace = c.assert = function () { };
    return c;
})();
/**
 * 判断当前对象内容是否包含中文
 */
String.prototype.hasChinese = function() {
	return (/.*[\u4e00-\u9fa5]+.*$/.test(this));
}

/**
 * 自定义字符串结尾判定方法，以s结尾返回true，否则返回false
 * @param s
 * @return
 */
String.prototype.endWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substring(this.length - s.length) == s)
		return true;
	else
		return false;
	return true;
}

/**
 * 自定义字符串开始判定方法，以s开始返回true，否则返回false
 * @param s
 * @return
 */
String.prototype.startWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substr(0, s.length) == s)
		return true;
	else
		return false;
	return true;
}

/**
 * IE浏览器兼容jquery trim方法
 * @return
 */
/*String.prototype.trim=function(){
 *  //IE8
  	return this.replace(/(^\s*)|(\s*$)/g, "");
}*/



/**
 * 将本地图片 显示到浏览器上
 * @param sourceId input标签的id
 * @param targetId img的id
 * @param boxId IE浏览器下采用滤镜方式实现预览，滤镜盒子ID
 */
function preImg(sourceId, targetId, boxId) {
	var sourceSrc = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
	viewImgBySource(sourceSrc,targetId,boxId);
}

function viewImgBySource(sourceSrc,targetId,boxId){
	if (navigator.userAgent.indexOf("MSIE") > -1) {
        try {
            document.getElementById(targetId).src = sourceSrc;
        } catch (e) {
            var div = document.getElementById(boxId)== undefined ? document.getElementById(targetId).parentNode : document.getElementById(boxId);
            this.select();
            top.parent.document.body.focus();
            var src = document.selection.createRange().text;
            document.selection.empty();
            document.getElementById(targetId).style.display = "none";
            div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
        }
    } else {
        document.getElementById(targetId).src = sourceSrc;
    }
}

/**
 * 判断当前客户端浏览器是否是IE8及以下浏览器
 * @return
 */
//function IE8LowerTest(){
//	 //检测浏览器版本
//	return $.browser.msie&&(parseInt($.browser.version)<=8);
//}

/**
 * 获取地址栏url参数
 * @param name
 * @return
 */
function getUrlParam(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

/**
 * 将信息复制到剪切板
 * 浏览器复制命令，支持从input或者textarea中进行取值，所以采用创建隐式textarea，然后选择执行复制命令
 * @param info
 * @return
 */
function copyToClipboard(info){
	var body = document.getElementsByTagName("body")[0];  
	var textArea = document.createElement("textarea");  
	textArea.setAttribute("id","text-area");
	//设置文本域隐藏
	textArea.style.cssText = "overflow:hidden; width:0; height:0;border:0; outline: none;"; 
	body.appendChild(textArea);  
	textArea.value = info;
	//var selectUrl = document.getElementById("text-area");
	textArea.select(); // 选择对象
	document.execCommand("Copy"); // 执行浏览器复制命令
	var pageType = getUrlParam("pageType");
	if(!isNull(pageType) && "en" == pageType){
		alert("copy citation success");
	}
	else alert("复制成功");
}


/**
 * 封装判断对象为空方法
 * @param object
 * @return
 */
function isNull(object){
	return typeof(object) == "undefined" || object == null || object == ""; 
}

/**
 * 获取随机数
 * @param Min
 * @param Max
 * @return
 */
function GetRandomNum(Min,Max){   
	var Range = Max - Min;   
	var Rand = Math.random();   
	return(Min + Math.round(Rand * Range));   
} 

/**
 * 获取网页顶部显示需要的日期信息
 * @param type 1:中文  2英文 3英文简写
 * 	  2017-1-11 星期三
 * 	  Wednesday, 11 January, 2017 
 *    Jan 20th, Wednesday
 * @return
 */
function dateStr(type){
	var date = new Date();
	return parseInt(type) == 1 ? 
		formatDate(date,type) + " "+ getTodayWeek(type) : 
		getTodayWeek(type) + ", " +formatDate(date,type)  ;
}


/**
 * 将日期格式化成英文格式
 * 2017-1-11
 * 11 January, 2017
 * Jan 11, 2017
 * @param date
 * */
function formatDate(date,type){
	if(!isNull(date)){
		var dateStr = JSON.stringify(date).substring(1,11);
		var dateVal = dateStr.split("-");
		var month = dateVal[1];
		if(month.charAt(0)== 0){month = month.charAt(1);}
		var monthArray = new Array
        ("January","February","March","April","May","June","July","August",
        "September","October","November","December");
		var monthArraySimple = new Array
        ("Jan","Feb","Mar","Apr","May","June","July","Aug",
        "Sep","Oct","Nov","Dec");
        switch (type) { 
		    case 1 : 
	            return dateStr;
		    case 2 : 
		    	return dateVal[2]+" "+monthArray[month-1]+", "+dateVal[0];
		    case 3 : 
		    	return monthArraySimple[month-1]+" "+dateVal[2]+", "+dateVal[0];
		}
 	}
}

/**
 * 获取星期几
 * @param type 1:中文  2英文 3英文简写
 * @return
 */
function getTodayWeek(type){
	var chinese = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");  
	var english = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");  
	var englishSigle = new Array("Sun.","Mon.", "Tues.", "Wed.", "Thur.", "Fri.", "Sat.");  
	var week = new Date().getDay(); 
	switch (type) { 
	    case 1 : 
            return chinese[week];
	    case 2 : 
	    	return english[week];
	    case 3 : 
	    	return englishSigle[week];
	}  
}


/**
 * 获取当前年
 * @returns
 */
function getCurrentYear(){
	var date = new Date();
	return date.getFullYear();
}

/**
 * 获取当前月
 * @returns
 */
function getCurrentMonth(){
	var date = new Date();
	return date.getMonth() + 1;
}


/**
 * 日期格式化
 * @param date
 * @returns
 */
function dateformatter(date){
	var y = date.getFullYear();
	var m = date.getMonth()+1;
	var d = date.getDate();
	return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
}

/**
 * 时间格式化
 * @param date
 * @returns
 */
function datetimeformatter(date) {
	var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
	var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0"
	+ (date.getMonth() + 1);
	var hor = date.getHours();
	var min = date.getMinutes();
	var sec = date.getSeconds();
	return date.getFullYear() + '-' + month + '-' + day+" "+hor+":"+min+":"+sec;
}

/**
 * 日期解析
 * @param s
 * @returns
 */
function myparser(s){
	if (!s) return new Date();
	var ss = (s.split('-'));
	var y = parseInt(ss[0],10);
	var m = parseInt(ss[1],10);
	var d = parseInt(ss[2],10);
	if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
		return new Date(y,m-1,d);
	} else {
		return new Date();
	}
}



/**
 * 通用下拉数据
 */
var commonJson = {
	"taskType":[{"label":"更新页面","value":"com.shy.task.quartz.job.impl.AutoCustomPageJob"},
			{"label":"数据发布","value":"com.shy.task.quartz.job.impl.ReleaseArticleJob"},
			{"label":"自动发文","value":"com.shy.task.quartz.job.impl.AutoPostJob"},
			{"label":"发网易同名","value":"com.shy.task.quartz.job.impl.PostWangYiJob"},
			{"label":"公众号数据","value":"com.shy.task.quartz.job.impl.GzhDataPostJob"},
			{"label":"对接图书","value":"com.shy.task.quartz.job.impl.BookSyncJob"},
			{"label":"百度提交","value":"com.shy.task.quartz.job.impl.BaiduPostJob"},
			{"label":"网站监控","value":"com.shy.task.quartz.job.impl.SiteCheckJob"},
			{"label":"访问统计","value":"com.shy.task.quartz.job.impl.StoreVisitInfo2DbJob"}],
	"viewType":[{"label":"生成静态","value":1},{"label":"动态浏览","value":2}],
    "status":[{"label":"有效","value":1},{"label":"无效","value":-1}],
    "tof":[{"label":"是","value":'1'},{"label":"否","value":'0'}],
    "channel":[{"label":"男频","value":1},{"label":"女频","value":2}],
    "serialStatus":[{"label":"连载中","value":1},{"label":"已完结","value":2}],
    "flags":[{"label":"头条","value":'h'},{"label":"推荐","value":'c'},{"label":"幻灯","value":'f'},{"label":"特荐","value":'a'},{"label":"图片","value":'p'},{"label":"排行榜","value":'t'}
	    ,{"label":"榜1","value":'b1'},{"label":"榜2","value":'b2'},{"label":"榜3","value":'b3'},{"label":"榜4","value":'b4'},{"label":"榜5","value":'b5'}
	    ,{"label":"榜6","value":'b6'},{"label":"榜7","value":'b7'},{"label":"榜8","value":'b8'},{"label":"榜9","value":'b9'},{"label":"榜10","value":'bx'}],
    "bookFlags":[{"label":"独家","value":'d'},{"label":"力荐","value":'l'},{"label":"热门","value":'r'},{"label":"火热","value":'h'},{"label":"强推","value":'q'}]
};

//年份  
var date = new Date();
//获取当前年份
var currentYear = date.getFullYear();
var yearJson = [];
for (var i = currentYear - 5; i <= currentYear + 5; i++) {
	yearJson.push({ "label" : i, "value" : i});
}
commonJson["year"] = yearJson;
//月份
var monthJson = [];
for(var m = 1; m <= 12; m++){
	monthJson.push({ "label" : m, "value" : m});
}
commonJson["month"] = monthJson;


/**
 * 获取通用下拉信息
 * @param info 数据名
 * @param addNull 是否添加空选項
 * @returns
 */
function getCommonInfoList(info, addNull){
	//var json = commonJson[info];
	var json = jQuery.extend(true, [], commonJson[info]);
	if(addNull){
		json.unshift({"value" : "","label" : '请选择'});
	}
	return json;
}


/**
 * 通用格式化输出
 * @param info
 * @param value
 * @returns
 */
function commonFormat(info, value){
	var formatVal = value;
	$.each(commonJson[info], function(i,e){
		if(e["value"] == value){
			formatVal = e["label"];
			return;
		}
	})
	return formatVal;
}

/**
* 格式化状态
*/
function formatStat(value, rowdata, index) {
	return commonFormat("status", value);
}

/**
 * 格式化连载状态
 * @param value
 * @param rowdata
 * @param index
 * @returns
 */
function formatSerial(value, rowdata, index) {
	return commonFormat("serialStatus", value);
}

//驗證手机號格式是否正確
function verifyMobilePhoneNumber(number){
	var flag = false;
	var reg = /^1[3-9]\d{9}$/;
	if(reg.test(number)){
		flag = true;
	}
	return flag;
}


//驗證邮箱格式是否正確
function verifyEmail(email){
	var flag = false;
	var reg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
	if(reg.test(email)){
		flag = true;
	}
	return flag;
}

/**
 * 暂定时间单位毫秒
 * @param d
 * @returns
 */
function sleep(d){
	for(var t = Date.now();Date.now() - t <= d;);
}


$(function(){
	//添加一个验证类型
	$.extend($.fn.validatebox.defaults.rules, {
		//combox必填校驗
	    comboxRequired: {
	        validator: function(value){
	            return value != "" && value != "请选择";
	        },
	        message: '请选择一个选项'
	    },
	    codeValid: {
	        validator: function(value){
	            return !value.hasChinese();
	        },
	        message: '代码不可包含漢字'
	    },
	    IsEmail:{
	        validator: function(value, param){
		         return	verifyEmail(value);
	        },   
	        message: '请輸入正確的邮箱'
		},
		IsMobilePhone: { 
			//验证手机号 
			validator: function(value, param){
				return	verifyMobilePhoneNumber(value);
	        },   
	        message: '请輸入正確的手机號'  
		 }
	});
})